package com.rockcent.message.util;

import com.alibaba.fastjson.JSON;
import com.rockcent.message.bean.WxAppTemplate;
import com.rockcent.message.bean.WxTemplate;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.MessageFormat;

/**
 * Created by zhangjh on 2017/7/18.
 */
public class WeixinTemplateUtil {


    private static Logger log = LoggerFactory.getLogger(WeixinTemplateUtil.class);

    // 发送模板的地址

    public final static String weiXinSenurl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}";
    public final static String weiAppSenurl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={0}";

    /**
     * 发送模板消息
     *
     * @param obj
     * @param accessToken
     * @return
     */
    public static int sendMessage(WxTemplate obj, String accessToken, String url) {
        int result = 0;
        String newUrl = MessageFormat.format(url, accessToken);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String json = JSON.toJSONString(obj);
//        log.info("-------------------------------------json:{}", json);
        try {
            HttpPost httpPost = new HttpPost(newUrl);
            StringEntity entity = new StringEntity(json, "UTF-8");
//            entity.setContentEncoding("UTF-8");
            httpPost.setEntity(entity);
            httpPost.setHeader("Accept", "application/json");
//            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
            response = httpclient.execute(httpPost);
            HttpEntity entityResp = response.getEntity();
            if (entityResp != null) {
//                log.info("--------------------------------------");
                log.info("Response content: " + EntityUtils.toString(entityResp, "UTF-8"));
//                log.info("--------------------------------------");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {

            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }


        return result;
    }


}
